package com.test.hanlp.participle.common.utils;

import org.apache.poi.ss.usermodel.Workbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author : ky.zhang
 * @description :Excel工具类
 * @createDate : 2024/8/9 14:12
 */
public class ExcelUtil {

    /**
     * @param exportPath       导出目录
     * @param downloadFileName 导出文件名
     * @return 导出文件
     */
    public static File createDatafile(String exportPath, String downloadFileName) throws IOException {
        // 创建目录
        Path path = Paths.get(exportPath);
        Files.createDirectories(path);

        // 创建文件
        File myFile = new File(path.toString(), downloadFileName);
        if (!myFile.exists()) {
            boolean fileCreated = myFile.createNewFile();
            if (!fileCreated) {
                throw new IOException("Failed to create file: " + myFile.getAbsolutePath());
            }
        }
        return myFile;
    }

    /**
     * 写入数据
     */
    public static void writeDownloadFileData(File saveFile, Workbook workbook) throws IOException {
        try (FileOutputStream outputStream = new FileOutputStream(saveFile)) {
            workbook.write(outputStream);
        }
        workbook.close();
    }
}